<?php
/**
 * Created by PhpStorm.
 * User: Admin
 * Date: 2019/11/14
 * Time: 14:18
 */

namespace DuRequest\Checker\lib;


use DuRequest\Checker\lib\base\RuleInterface;
use Request\Checker\lib\RequestData;

class Rule implements RuleInterface
{
    /**
     * @var Checker[]
     */
    public $rule ;

    /**
     * @var array
     */
    public $errors = [];

    public $is_validate = true;

    /**
     * @var RequestData
     */
    public $request_data;

    /**
     * Rule constructor.
     * @param $rule Checker[]
     * @param $request_data RequestData
     */
    public function __construct($rule , $request_data)
    {
        $this->setRule( $rule );
        $this->request_data = $request_data;
    }

    public function setRule($rule)
    {
        $this->rule = $rule;
    }

    public function validate(){
        return $this->run();
    }

    public function run()
    {
        if(!empty($this->rule)){
            foreach ($this->rule as $checker){
                $checker->setRequestData($this->request_data);
                if(!$checker->validate()){
                    $this->errors[] = [
                        'key' => $checker->getKey(),
                        'msg' => $checker->getError(),
                    ];
                    $this->setValidate( false );
                }
            }
        }
        return $this->getValidate();
    }

    public function setValidate( $validate ){
        $this->is_validate = $validate;
    }

    public function getValidate(){
        return $this->is_validate;
    }

    public function getErrors()
    {
        return $this->errors;
    }

    public function getFirstError()
    {
        if(empty($this->errors)){
            return null;
        }
        return array_pop($this->errors);
    }

}